<?php

//list taken from /cake/libs/validation.php line 497 
if (!defined('DEFAULT_VALIDATION_EXTENSIONS')) {
    define('DEFAULT_VALIDATION_EXTENSIONS', 'gif,jpeg,png,jpg');
}

class ValidationHelper extends Helper {
    
    var $helpers = array('Html', 'Js');

    function rules($modelName, $options = array()) {
        if (empty($options) || !is_array($options) || empty($options['formId'])) {
            return false;
        }
        
        $scriptTags = '';
        
        $class = APP . 'Model/' . $modelName . '.php';
        if (!file_exists($class)) {
            return false;
        }
        
        if (!class_exists($modelName)) {
            require_once($class);
        }
        
        $model = new $modelName();

        $defaultOptions = array('formId' => false, 'inline' => false);
        $options = array_merge($defaultOptions, $options);

        $formId = '#' . $options['formId'];
        
        $scriptTags.= "$(document).ready(function() {\n";
        $scriptTags.= "$('" . $formId . "').submit( function() { return validateForm('" . $modelName . "', this, rules); });\n";
        $scriptTags.= '$("#dialog-modal-errores").kendoWindow({
                            width: 400,
                            modal: true,
                            draggable: false,
                            title: "Atención",
                            visible: false,
                            show: "fadeIn",
                            hide: "fadeOut"
                       });' . "\n";
        $scriptTags.= "});\n";
        
        $js = "var rules = Array(";

        foreach ($model->validate as $field => $validators) {
            $js.= "['" . $field . "', [";

            foreach ($validators as $key => $validator) {
                if (!is_array($validator)) {
                    $validator = array('rule' => $validator);
                }

                $mensaje = $validator['message'];
                if (!isset($mensaje)) {
                    $mensaje = sprintf('%s %s', __('Hubo un problema con el campo', true), Inflector::humanize($field));
                }

                $rule = $validator['rule'];
                if (is_array($rule)) {
                    $rule = $rule[0];
                }

                $js.= "['" . $mensaje . "', '" . $rule . "'],";
            }

            $js = substr($js, 0, strlen($js) - 1);
            $js.= "]],";
        }
        
        $js = substr($js, 0, strlen($js) - 1);
        $js.= ");";
        
        $scriptTags.= $js."\n";

        $this->Html->scriptBlock($scriptTags, array('inline' => false));

        return true;
    }

}
